<?php

declare(strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use app\model\Customer;
use app\model\CustomerFollow;

class Task extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('task')
            ->setDescription('the task command');
    }

    protected function execute(Input $input, Output $output)
    {
        $models = CustomerFollow::field(['id', 'customer_id', 'started_at', 'ended_at'])->where('status_value', '1')->whereTime('ended_at', '<', date('Y-m-d H:i:s'))->select();

        foreach ($models as $model) {
            // 获取已终止记录编号
            $customer_follow = CustomerFollow::where('customer_id', $model->customerId)->where('status_value', '2')->findOrEmpty();
            if ($customer_follow->isEmpty()) {
                // 创建已终止记录
                $customer_follow = new CustomerFollow();
                $customer_follow->customerId = $model->customerId;
                $customer_follow->statusValue = '2';
                $customer_follow->startedAt = $model->startedAt;
                $customer_follow->endedAt = $model->endedAt;
                $customer_follow->electricityConsumption = 0;
                $customer_follow->save();
            }

            // 更新客户的跟进记录编号
            Customer::where('id', $model->customerId)->update(['customer_follow_id' =>  $customer_follow->id]);

            // 指令输出
            $output->writeln('更新客户记录状态成功');
        }
    }
}
